package org.juc.readwirtelock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 模拟缓存
 *
 * @author bobby
 * @date 2021/11/24
 */
class Cache{
    private volatile Map<String,Object> cache  =  new HashMap<>();
    final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    /**
     * 写入方法
     *
     * @param key   关键
     * @param value 价值
     */
    public void put(String key,Object value){
        try {
            readWriteLock.writeLock().lock();
            System.out.println(Thread.currentThread().getName()+"\t --- 写入数据\t"+key);
            cache.put(key,value);
            TimeUnit.MILLISECONDS.sleep(300);
            System.out.println(Thread.currentThread().getName()+"\t 写入数据完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }

    /**
     * 读取方法
     *
     * @param key 键
     */
    public void get(String key){
        try {
            readWriteLock.readLock().lock();
            System.out.println(Thread.currentThread().getName()+"\t 读取数据");
            // 模拟网络延迟300毫秒
            TimeUnit.MILLISECONDS.sleep(300);
            Object value = cache.get(key);
            System.out.println(Thread.currentThread().getName()+"\t 读取数据完成\t"+value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
        }
    }
}

/**
 * 读写锁演示
 *
 * @author bobby
 * @date 2021/11/24
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        // 资源类
        Cache cache = new Cache();
        // 开5个线程去进行写入操作
        for (int i = 1; i <= 5; i++) {
            final  int temInt = i;
            new Thread(()->{
                cache.put(String.valueOf(temInt),temInt);
            },String.valueOf(i)).start();
        }
        // 开5个线程去进行读取操作
        for (int i = 1; i <= 5; i++) {
            final  int temInt = i;
            new Thread(()->{
                cache.get(String.valueOf(temInt));
            },String.valueOf(i)).start();
        }
    }
}
